package com.cy.jt.security.util.config.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

public class DefaultAccessDeniedExceptionHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest,
                       HttpServletResponse httpServletResponse,
                       AccessDeniedException e) throws IOException, ServletException {
//            httpServletResponse.sendRedirect("http://www.tesu.cn");
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType("application/json;charset=utf-8");
        PrintWriter out = httpServletResponse.getWriter();
        HashMap<Object, Object> map = new HashMap<>();
        map.put("state", HttpServletResponse.SC_FORBIDDEN);
        map.put("message", "没有访问权限，请联系管理员");
        String jsonStr = new ObjectMapper().writeValueAsString(map);
        out.println(jsonStr);
        out.flush();
    }
}
